package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void addOrderSettingList(List<OrderSetting> orderSettingList) {
        if(orderSettingList != null && orderSettingList.size() > 0){
            for (OrderSetting orderSetting : orderSettingList) {
                saveOrEdit(orderSetting);
            }
        }
    }

    @Override
    public List<OrderSetting> findByMonth(String date) {
        //2020-02-01
        String thisMonthFirstDay = date + "-01";
        Date thisMonthLastDayDate = DateUtils.getThisMonthLastDay(thisMonthFirstDay);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String thisMonthLastDay = sdf.format(thisMonthLastDayDate);
        return orderSettingDao.findByMonth(thisMonthFirstDay,thisMonthLastDay );

    }

    /**
     * 思路：
     *  判断该日期是否进行预约设置
     *  如果已经预约设置，则修改
     *      修改时，需要判断 已预约人数 是否大于可预约人数
     *          如果大于可预约人数，则提示错误信息
     *          否则，修改预约设置
     *  如果没有预约设置，则添加
     *
     * 步骤：
     *   1. 根据预约日期查询预约设置对象
     *   2. 如果预约设置对象为null，则新增
     *   3. 如果预约设置对象不为null
     *      判断 已预约人数 是否大于可预约人数，如果大于，抛出运营异常
     *      否则，更新数据库
     * @param orderSetting
     */
    @Transactional
    public void saveOrEdit(OrderSetting orderSetting){
        OrderSetting orderSettingDb = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
        if(orderSettingDb == null){
            orderSettingDao.add(orderSetting);
        }else{
            if(orderSettingDb.getReservations() > orderSetting.getNumber()){
                throw new BusinessRuntimeException("已预约人数不能大于可预约人数!!!");
            }else{
                orderSettingDao.edit(orderSetting);
            }
        }
    }
}
